import api from '../../../api-new'
import types from '../../types'

export const search = ({ commit, state }, { keyword, keyname, pageNumber }) => {
  if (
    state.keyword === keyword &&
    state.keyname === keyname &&
    state.data.pageNum === pageNumber
  ) return

  if (state.keyword !== keyword) {
    commit(types.SEARCH_RESET)
    pageNumber = 1
  }

  commit(types.SEARCHING, true)
  console.log(keyname, keyword)
  api.search(keyname, keyword, pageNumber).then(data => {
    commit(types.SEARCHING, false)
    commit(types.SEARCH, { ...data, keyword, keyname })
  }).catch(err => {
    commit(types.SEARCHING, false)
    console.error(err)
    window.alert(err.message)
  })
}

export const getSubLibs = ({ commit, state }) => {
  api.subLibs().then(response => {
    if (response.data.status === 1) {
      commit(types.SUB_LIBS, response.data.results)
    }
  }).catch(error => {
    console.log(error)
  })
}
